package com.skymxc.demo.explorer;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.skymxc.demo.explorer.adapter.FileListPagerAdapter;
import com.skymxc.demo.explorer.entity.PageTab;
import com.skymxc.demo.explorer.util.DBUtil;
import com.skymxc.demo.explorer.util.SettingUtil;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String  TAG ="MainActivity";

    private static final int REQUEST_SETTING =10;

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager pager;
    private FileListPagerAdapter adapter;
    private List<PageTab> tabs;
    private Menu menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String theme = SettingUtil.getTheme(this);
        switch (Integer.parseInt(theme)){
            case 0:
               // getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                break;
            case 1:
                getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                break;
        }
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        pager = (ViewPager) findViewById(R.id.view_pager);

        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");

        //初始化数据
        tabs= DBUtil.loadTabs();
        adapter = new FileListPagerAdapter(getSupportFragmentManager(),tabs);
        pager.setAdapter(adapter);
        tabLayout.setupWithViewPager(pager,true);
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
             findCurrentFragment().setToolBarTitle();

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        tabLayout.addOnTabSelectedListener(onTabSelectedListener);


    }

    private TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
           int position= tab.getPosition();
            TabFragment fragment = findCurrentFragment(position);
            if (fragment!=null){
                fragment.hideActionMode();
            }

            if(menu!=null){
                menu.removeGroup(10);
            }
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e(TAG,"========onActivityResult()=======");
        if (requestCode==REQUEST_SETTING && resultCode == RESULT_OK){
            refreshAllFragment();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu=menu;
        getMenuInflater().inflate(R.menu.menu_unselect,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.order_date:
           case R.id.order_name:
           case R.id.order_size:
           case R.id.order_type:
               SettingUtil.setSortType(this,item.getItemId());
               refreshAllFragment();
                break;
            case R.id.new_directory:
                create(R.id.new_directory);
                break;
            case R.id.new_file:
                create(R.id.new_file);
                break;
            case R.id.new_root_tab:
                createRootTab();
                break;
            case R.id.close_current_tab:
                closeCurrentTab();
                break;
            case R.id.flush:
               findCurrentFragment().refresh();
                break;
            case R.id.return_main:
                findCurrentFragment().returnMain();
                break;
            case R.id.exit:
                finish();
                break;
            case R.id.setting:
                SettingActivity.startActivityForResult(this,REQUEST_SETTING);
                break;
            case android.R.id.paste:
                //fragment的move
                findCurrentFragment().move();
                menu.removeGroup(10);
                break;
            case android.R.id.undo:
                menu.removeGroup(10);
                break;

        }

        return true;
    }



    @Override
    public void onBackPressed() {
        if (findCurrentFragment().onBackPressed()){
            super.onBackPressed();
        }

    }

    /**
     * 关闭当前根标签
     */
    private void closeCurrentTab() {
        int count = DBUtil.getCount();
        int position = tabLayout.getSelectedTabPosition();
        if (count>1){

            adapter.removeTab(position);
            //pager.setCurrentItem(0);
        }else{
            Toast.makeText(this,"当前只有一个根标签了，无法删除，实在不行你退出吧",Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 新建根标签
     */
    private void createRootTab() {

        PageTab tab = new PageTab();
            tab.setName("根标签");
            tab.setMainPath(Environment.getExternalStorageDirectory().getPath());
        tab.setLastPath(Environment.getExternalStorageDirectory().getPath());
        tab.save();
        adapter.addTab(tab);

    }


    /**
     * 菜单打开触发
     * @param featureId
     * @param menu
     * @return
     */
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu!=null){
            //判断打开的是否是排序菜单
            MenuItem item = menu.findItem(SettingUtil.getSortType(this));
            if (item!=null){
               item.setChecked(true);
            }
        }
        return true;
    }



    /**
     * 新建 文件或者文件夹
     * @param type
     */
    private void create(final int type){
        String title ="新建文件夹";
        if (type==R.id.new_file){
            title = "新建文件";
        }

        final EditText editText = new EditText(this);

        new AlertDialog.Builder(this).setTitle(title)
                .setView(editText)
                .setNegativeButton("新建", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //获取当前Fragment
                        TabFragment fragment = findCurrentFragment();
                        if (fragment == null){
                            Log.e(TAG,"=create()==currentFragment:="+fragment);
                            return;
                        }
                        String reg ="[0-9a-zA-Z.]+";
                        String name = editText.getText().toString();
                        if (!name.matches(reg)){
                            Toast.makeText(MainActivity.this,"输入不合格",Toast.LENGTH_SHORT).show();
                            return;
                        }
                      if(fragment.createFile(type,name)){
                          Toast.makeText(MainActivity.this,"创建"+name+"成功",Toast.LENGTH_SHORT).show();
                         refreshAllFragment();
                      }else{
                          Toast.makeText(MainActivity.this,"创建"+name+"失败",Toast.LENGTH_SHORT).show();
                      }

                    }
                })
                .setNeutralButton("cancel",null)
                .show();

    }

    /**
     * 查询Fragment
     * @return
     */
    private  TabFragment findCurrentFragment(int position){
        Fragment fragment =  getSupportFragmentManager().findFragmentByTag("android:switcher:"+pager.getId()+":"+position);

       // Log.e(TAG,"=======findCurrentFragment=========当前显示的Fragment 的tag===:"+fragment.getTag());
        if (fragment instanceof TabFragment){
            return (TabFragment)fragment;
        }
        return null;
    }




    /**
     * 查询当前 显示的Fragment
     * @return
     */
    private  TabFragment findCurrentFragment(){
        return findCurrentFragment(pager.getCurrentItem());
    }

    /**
     * 刷新所有的Fragment
     */
    public void refreshAllFragment(){
        //获取所有Fragment 集合
     List<Fragment> fragments=   getSupportFragmentManager().getFragments();
        for (Fragment fragment :fragments){
            if (fragment instanceof TabFragment){
                //刷新
                ( (TabFragment)fragment).refresh();
            }
        }
    }

    /**
     * 移动文件
     */
    public void moveFile() {


        menu.add(10,android.R.id.paste,0,"粘贴");
        menu.add(10,android.R.id.undo,1,"取消");

     MenuItem paste=   menu.findItem(android.R.id.paste);
        paste.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
       // paste.setIcon(R.mipmap.ic_menu_copy);
        menu.findItem(android.R.id.undo).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

    }
}
